<!--
  -    Copyright (c) 2018-2025, lengleng All rights reserved.
  -
  - Redistribution and use in source and binary forms, with or without
  - modification, are permitted provided that the following conditions are met:
  -
  - Redistributions of source code must retain the above copyright notice,
  - this list of conditions and the following disclaimer.
  - Redistributions in binary form must reproduce the above copyright
  - notice, this list of conditions and the following disclaimer in the
  - documentation and/or other materials provided with the distribution.
  - Neither the name of the pig4cloud.com developer nor the names of its
  - contributors may be used to endorse or promote products derived from
  - this software without specific prior written permission.
  - Author: lengleng (wangiegie@gmail.com)
  -->
<template>
	<div class="execution">
		<basic-container>


			<avue-crud
				ref="crud"
				v-model="form"
				:page="page"
				:data="tableData"
				:permission="permissionList"
				:table-loading="tableLoading"
				:option="tableOption"
				:before-close="beforeClose"
				@on-load="getList"
				@search-change="searchChange"
				@refresh-change="refreshChange"
				@size-change="sizeChange"
				@current-change="currentChange"
				@row-update="handleUpdate"
				@row-save="handleSave"
				@row-del="rowDel"
			>
				<template v-slot:menu="{row, index}">
					<el-button
						style="background: none; border: none;color:#f56c6c"
						type="text"
						size="small"
						@click.stop="departure(row, index)">
						离职
					</el-button>
<!--					<el-button
						type="text"
						size="small"
						@click.stop="great(scope.row)">
						出彩新联人
					</el-button>-->
					<el-button type="text" size="small" @click="showUsre(row)">修改个人简介</el-button>
				</template>
				<template slot="menuLeft">
					<el-button type="primary" size="small" @click="structure">按组织架构批量导入</el-button>
					<el-upload class="plButton" action="/circleuser/import"
							   accept=".xlsx"
							   :show-file-list="false"
							   :headers="headers"
							   :on-success="uploadRes">
						<el-button type="success" size="small">批量导入</el-button>
					</el-upload>

					<!--          <el-upload class="plbdButton" action="/conversion/excel/inputForm/userForm" accept=".xls"-->
					<!--                     :show-file-list="false"-->
					<!--                     multiple-->
					<!--                     :headers = "headers"-->
					<!--                     :on-success="importForm">-->
					<!--            <el-button type="success" size="small">批量导入表单</el-button>-->
					<!--          </el-upload>-->


					<el-button type="info" size="small" @click="downLoadTemp">下载模板</el-button>
					<!--          <el-button type="info" size="small" @click="downLoadImg">扫码加入</el-button>-->
					<!--          <el-button type="info" size="small" @click="downLoadForm">导出表单</el-button>-->

					<!--          <el-button type="info" size="small" @click="downLoadList">导入任务</el-button>-->
				</template>
			</avue-crud>

			<!-- 批量导入错误信息弹窗 -->
			<el-dialog
				title="失败信息"
				:visible.sync="dialogVisible"
				width="70%"
			>
				<el-table :data="tableData1.slice((currentPage-1)*pagesize,currentPage*pagesize)"
						  style="width: 100%;margin-bottom:15px">
					<el-table-column prop="errorData.姓名" label="姓名" width="180"></el-table-column>
					<el-table-column prop="errorData.手机" label="手机" width="180"></el-table-column>
					<el-table-column prop="errorData.性别" label="性别" width="180"></el-table-column>
					<el-table-column prop="errorData.出生年份" label="出生年份" width="180"></el-table-column>
					<el-table-column prop="errorData.邮箱" label="邮箱"></el-table-column>
					<el-table-column prop="errorMsg" label="失败原因"></el-table-column>
				</el-table>
				<el-pagination
					@size-change="handleSizeChange"
					@current-change="handleCurrentChange"
					:current-page="currentPage"
					:page-sizes="10"
					:page-size="pagesize"
					:total="tableData1.length"
					layout="total, sizes, prev, pager, next, jumper"
				>
				</el-pagination>
			</el-dialog>

			<!-- 组织架构导入弹窗 -->
			<el-dialog
				title="组织架构导入"
				:visible.sync="structureDialog"
				width="70%"
			>
				<el-table
					default-expand-all
					border
					:data="menuList"
					row-key="id"
					:tree-props="{ children: 'circleOrganizationalVoList'}"
				>
					<el-table-column
						prop="name"
						label="菜单名称"
						:show-overflow-tooltip="true"
					></el-table-column>
					<el-table-column prop="createTime" label="创建时间"></el-table-column>
					<el-table-column
						label="操作"
						align="center"
						class-name="small-padding fixed-width"
					>
						<template slot-scope="scope">
							<el-upload class="plButton"
									   ref="upload"
									   :data="organizationalId"
									   :headers="headers"
									   action="/circleuser/importFileByOrganizationalId"
									   accept=".xlsx" :show-file-list="false" :on-success="uploadRes">
								<el-button type="text" size="small" @click="submitUpload(scope.row)">批量导入</el-button>
							</el-upload>
						</template>
					</el-table-column>
				</el-table>
			</el-dialog>

			<el-dialog
				title="导入任务"
				:visible.sync="importFormDialog"
				width="70%"
			>
				<avue-crud ref="crud"
						   :page="formPage"
						   :data="formTableData"
						   :table-loading="formTableLoading"
						   :option="formListOption"
						   @on-load="getFormList"
						   @search-change="formSearchChange"
						   @refresh-change="formRefreshChange"
						   @size-change="formSizeChange"
						   @current-change="formCurrentChange"
				>
					<template slot-scope="scope" slot="menu">

						<el-button
							style="background: none; border: none;"
							type="text"
							size="small"
							@click.stop="dowloadErrorForm(scope.row, scope.index)"
						>下载
						</el-button
						>


					</template>

				</avue-crud>
			</el-dialog>

		<el-dialog
			title="修改个人简介"
			:visible.sync="show"
			:before-close="handleClose">
			<avue-form style="width:100%" ref="userInfo" v-model="userInfo" :option="auditOption" @submit="handleSubmit"></avue-form>
		</el-dialog>

		</basic-container>
	</div>
</template>

<style scoped>
.plButton {
	display: inline-block;
}
</style>
<script>
import {fetchList, getObj, addObj, putObj, delObj, circlecompany, save} from '@/api/circleuser'
import {tableOption} from '@/const/crud/circleuser'
import {formListOption} from "@/const/crud/circleuserimportform";
import {fetchFromList} from "@/api/circleuserimportform";
import AvueUeditor from 'avue-plugin-ueditor'

import {mapGetters} from 'vuex'
import store from "@/store";

export default {
	name: 'circleuser',
	data() {
		return {
			form: {},
			dialogFlag: false,
			//组织架构导入错误信息分页
			organizationalId: {
				oid: ''
			},
			organizational: [],
			// 菜单表格树数据
			menuList: [],
			//组织架构导入错误信息弹窗
			structureDialog: false,
			//批量导入错误信息分页
			tableData1: [],

			//导入任务弹窗
			importFormDialog: false,
			currentPage: 1,
			pagesize: 10,
			headers: {
				Authorization: 'Bearer ' + store.getters.access_token
			},
			//批量导入错误信息弹窗
			dialogVisible: false,
			errorData: {},
			errorMsg: '',
			searchForm: {},
			tableData: [],
			formTableData: [],
			page: {
				total: 0, // 总页数
				currentPage: 1, // 当前页数
				pageSize: 20 // 每页显示多少条
			},
			formPage: {
				total: 0, // 总页数
				currentPage: 1, // 当前页数
				pageSize: 10 // 每页显示多少条
			},
			tableLoading: false,
			tableOption: tableOption,
			formTableLoading: false,
			formSearchForm: {},

			formListOption: formListOption,

			show: false,
			userInfo: {},
			auditOption: {
				menuPosition:'right',
				emptyBtn:false,
				column: [
					{
						type: 'textarea',
						"label": "个人简介",
						"prop": "introduce",
						maxlength: "10000",
						rules: [{
							required: true,
							message: "请输入个人简介",
							trigger: "blur"
						}]
					}, {
						span: 22,
						"type": "upload",
						"label": "照片墙",
						"prop": "pic",
						listType: 'picture-card',
						accept: ["image/png", "image/jpeg"],
						action: "/fastfile/upload/hsh-1251035051",
						fileSize: 500000,
						dataType: "string",
						propsHttp: {
							res: "data",
							url: "kpath"
						},
						tip: "只能上传jpg/png文件，且不超过500kb",
						rules: [{
							required: true,
							message: "请上传图片",
							trigger: "blur"
						}]
					},
				]
			}
		}
	},
	watch: {
		// 'form.chucai': {
		// 	handler(val) {
		// 		var img = this.findObject(this.tableOption.column, 'img')
		// 		var desc = this.findObject(this.tableOption.column, 'description')
		// 		var sortBy = this.findObject(this.tableOption.column, 'sortBy')
		// 		if(val===1){
		// 			img.display=true;
		// 			desc.display=true;
		// 			sortBy.display=true;
		// 		}else {
		// 			img.display=false;
		// 			desc.display=false;
		// 			sortBy.display=false;
		// 		}
		// 	},
		// 	immediate: true
		// },
		// 'form.endTime': {
		//   handler(val) {
		//     val = val.replace(/-/g, '/');
		//     let time = new Date(val);
		//     let dangqian = new Date();
		//     console.log(val, this.form)
		//     if (time < dangqian) {
		//       this.$message.warning('结束时间不能小于当前时间！！！')
		//     }
		//   },
		//   immediate: true
		// },
	},
	computed: {
		...mapGetters(['permissions']),
		permissionList() {
			return {
				addBtn: this.vaildData(this.permissions.circleUser_circleuser_add, false),
				delBtn: this.vaildData(this.permissions.circleUser_circleuser_del, false),
				editBtn: this.vaildData(this.permissions.circleUser_circleuser_edit, false)
			};
		},

	},
	created () {
	},
	methods: {
		beforeClose(done, type) {
			if (type == "add" || type == "edit") {
				if (this.dialogFlag == true) {
					done()
				}
				if (this.dialogFlag == false) {
					this.$confirm("可能有未保存的数据，是否关闭", '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					}).then(data => {
						done()
					}).catch(_ => {
						// done()
					});
				}
			} else {
				done()
			}

		},
		//组织架构导入
		structure() {
			this.structureDialog = true
			axios.get('/circleorganizational/page/list').then(res => {
				this.menuList = res.data.data;
			})
		},
		// 批量导入错误信息展示
		handleSizeChange: function (val) {
			this.pagesize = val;
		},
		handleCurrentChange: function (currentPage) {
			this.currentPage = currentPage;
		},

		uploadRes(response, file, fileList) {
			if (response.code === 0) {
				this.$message.success("导入成功");
				this.refreshChange();
			} else {
				var vm = this
				vm.tableData1 = response.data
				this.$message.error("导入失败");
				setTimeout(() => {
					vm.dialogVisible = true
				}, 1000)
			}
		},

		importForm(response, file, fileList) {
			this.$message.success("导入成功");
			this.refreshChange();
		},
		submitUpload(row) {
			console.log(row.id)
			this.organizationalId.oid = row.id
		},
		//  uploadRes1(response, file, fileList){
		//     if(response.code===0){
		//         this.$message.success("导入成功");
		//         this.refreshChange();
		//     }else{
		//       var vm = this
		//       vm.tableData1 = response.data
		//       this.$message.error("导入失败");
		//       setTimeout(()=>{
		//         vm.dialogVisible = true
		//       },1000)
		//     }
		// },
		//下载模板
		downLoadTemp() {
			window.location.href = 'file/人员信息模板.xlsx';
		},
		downLoadImg() {
			axios.get('circleuser/scan/add/qr').then(res => {
				// window.location.href = res.data.data
				console.log(res.data.data)
				var url = res.data.data
				var a = document.createElement('a');          // 创建一个a节点插入的document
				var event = new MouseEvent('click')           // 模拟鼠标click点击事件
				a.download = 'beautifulGirl'                  // 设置a节点的download属性值
				a.href = url;
				a.target = '_blank'                           // 将图片的src赋值给a节点的href
				a.dispatchEvent(event)
			})

		},

		downLoadForm() {
			window.open('/import/export')
		},

		departure(row) {
			var vm = this
			vm.$confirm('是否确认离职', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(function () {
				axios.get('/circleuser/theCancellation?uid=' + row.id).then(res => {
					vm.$message.success('成功')
					vm.getList(vm.page)
				})
			})
		},
		great(row){

		},
		getList(page, params) {
			var vm = this
			vm.tableLoading = true
			fetchList(Object.assign({
				current: page.currentPage,
				size: page.pageSize
			}, params, vm.searchForm)).then(response => {
				var records = response.data.data.records;
				records.map(r => {
					if (r.organizationalId) {
						r.organizationalId = parseInt(r.organizationalId)
					}
					r.birthYear += '';
					if (r.circleCompany) {
						let arr = [];
						JSON.parse(r.circleCompany.pic).forEach(i => {
							arr.push(i.url)
						})
						r.picArr = arr.toString();
					}
					return r;
				});
				console.log(records)
				vm.tableData = records
				vm.page.total = response.data.data.total
				vm.tableLoading = false
			}).catch(() => {
				vm.tableLoading = false
			})
		},
		rowDel: function (row, index) {
			this.$confirm('是否确认删除ID为' + row.id, '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(function () {
				return delObj(row.id)
			}).then(data => {
				this.$message.success('删除成功')
				this.getList(this.page)
			})
		},
		handleUpdate: function (row, index, done, loading) {
			if (row.birthYear) {
				row.birthYear = parseInt(row.birthYear);
			}
			if (row.organizationalId) {
				row.organizationalId = row.organizationalId.toString()
			}
			putObj(row).then(data => {
				this.$message.success('修改成功')
				this.dialogFlag = true
				done()
				this.getList(this.page)
			}).catch(() => {
				loading();
			});
			setTimeout(() => {
				this.dialogFlag = false
			}, 500)
		},
		handleSave: function (row, done, loading) {
			if(typeof row.img === 'object'){
				row.img='';
			}
			addObj(row).then(data => {
				this.$message.success('添加成功')
				this.dialogFlag = true
				done()
				this.getList(this.page)
			}).catch(() => {
				loading();
			});
			setTimeout(() => {
				this.dialogFlag = false
			}, 500)
		},
		sizeChange(pageSize) {
			this.page.pageSize = pageSize
		},
		currentChange(current) {
			this.page.currentPage = current
		},
		searchChange(form, done) {
			this.searchForm = form
			this.page.currentPage = 1
			this.getList(this.page, form)
			done()
		},
		refreshChange() {
			this.getList(this.page)
		},
		downLoadList() {
			this.importFormDialog = true;
		},

		getFormList(page, params) {
			this.formTableLoading = true
			fetchFromList(Object.assign({
				current: page.currentPage,
				size: page.pageSize
			}, params, this.searchForm)).then(response => {
				this.formTableData = response.data.data.records
				this.formPage.total = response.data.data.total
				this.formTableLoading = false
			}).catch(() => {
				this.formTableLoading = false
			})
		},
		formSearchChange(form, done) {
			this.formSearchForm = form
			this.formPage.currentPage = 1
			this.getFormList(this.formPage, form)
			done()
		},
		formRefreshChange() {
			this.getFormList(this.formPage);
		},
		formSizeChange(pageSize) {
			this.formPage.pageSize = pageSize
		},
		formCurrentChange(current) {
			this.formPage.currentPage = current
		},
		dowloadErrorForm(row, index) {
			let data = row.filePath;
			if (data == null || data == '') {
				this.$message.error("请等待任务完成,再进行下载预览")
			} else {
				window.open('/import/download?path=' + data);
			}
		},
		showUsre (row) {
			this.show = true
			this.form = row
			if (row.circleCompany) {
				this.circlecompany(row.circleCompany.id)
			}
		},
		circlecompany(id) {
			circlecompany(id).then(res => {
				this.userInfo = res.data.data
				this.userInfo.pic = JSON.parse(res.data.data.pic).map(v => {
					return v.url
				}).join(',')
			})
		},
		handleClose () {
			this.show = false
			this.$refs.userInfo.resetForm()
		},
		handleSubmit (form, done) {
			const arr = form.pic.split(',').map(v => {
					return {
						url: v
					}
				})
			const data = {
				uid: this.form.id,
				introduce: form.introduce,
				pic: JSON.stringify(arr)
			}
			save(data).then(res => {
				console.log(res)
				this.$message.success('保存成功!')
				done()
				this.handleClose()
				this.getList(this.page)
			})
		},

	}
}
</script>
